package com.boot.main.config.configDemo;

import cn.hutool.json.JSONUtil;
import com.boot.main.utils.IsNotEmptyUtil;
import com.boot.main.entity.CcomSyslog;
import com.boot.main.jwt.JwtUtils;
import com.boot.main.mapper.CcomSyslogMapper;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Aspect
@Component
public class SysLogAspect {
//    https://www.cnblogs.com/smallfa/p/13785880.html
    @Resource
    private CcomSyslogMapper syslogMapper;

    @Pointcut("@annotation(com.boot.main.config.configDemo.MyLog)")
    public void logPoinCut(){}

    @AfterReturning("logPoinCut()")
    public void saveSysLog(JoinPoint joinPoint){
        CcomSyslog syslog = new CcomSyslog();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MyLog myLog = method.getAnnotation(MyLog.class);
        if(myLog != null){
            String value = myLog.value();
            syslog.setOperation(value);
        }
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();
        syslog.setMethod(className + "." + methodName);

        Object[] args = joinPoint.getArgs();
        String params = JSONUtil.toJsonStr(args);
        syslog.setParams(params);
        syslog.setCreate_time(new Date().getTime());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("Authorization");
        if(IsNotEmptyUtil.isNotEmpty(token)){
            token = token.substring(7);
            String username = JwtUtils.getUsername(token);
            syslog.setUsername(username);
        }
        if(methodName == "login"){
            syslog.setUsername(args[0].toString().split("=")[1].split(",")[0]);
        }
        String ip = request.getRemoteAddr();
        syslog.setIp(ip);
        syslogMapper.saveSyslog(syslog);
    }
}
